package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnpc.ymz.bc.nfinmgmt.exception.BusinessException;
import ${package.Entity}.request.Find${entity}ByPageReq;
import ${package.Entity}.request.Find${entity}ListReq;
import ${package.Entity}.request.Del${entity}Req;
import ${package.Entity}.request.BatchDelete${entity}Req;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import com.codegen.QueryWrapperUtil;

/**
 * ${table.comment!} 仓库实现类
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

    /**
     * 分页查询${table.comment!}列表
     *
     * @param req 查询条件
     * @return 分页数据
     */
    @Override
    public Page<${entity}> find${entity}ByPage(Find${entity}ByPageReq req) {
        final LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
        final Page<${entity}> page = new Page<>(req.getPageNo(), req.getPageSize());
        // 构建查询条件
        QueryWrapperUtil.buildQueryCondition(queryWrapper, req, ${entity}.class);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询${table.comment!}列表
     *
     * @param req 查询条件
     * @return 列表数据
     */
    @Override
    public List<${entity}> find${entity}ListByCondition(Find${entity}ListReq req) {
        final LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        QueryWrapperUtil.buildQueryCondition(queryWrapper, req, ${entity}.class);
        return this.list(queryWrapper);
    }

    /**
     * 新增${table.comment!}
     *
     * @param ${entity?uncap_first} ${table.comment!}对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add${entity}(${entity} ${entity?uncap_first}) {
        try {
            // 执行新增
            final boolean success = this.save(${entity?uncap_first});
            if (!success) {
                throw new BusinessException("新增失败");
            }
        } catch (Exception e) {
            log.error("新增${table.comment!}失败", e);
            throw new BusinessException("新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改${table.comment!}
     *
     * @param ${entity?uncap_first} ${table.comment!}对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mod${entity}(${entity} ${entity?uncap_first}) {
        try {
            <#-- 检查主键字段数量 -->
            <#assign primaryKeyCount = 0>
            <#if table?? && table.fields??>
            <#list table.fields as field>
                <#if field.keyFlag?? && field.keyFlag>
                    <#assign primaryKeyCount = primaryKeyCount + 1>
                </#if>
            </#list>
            </#if>
            
            // 检查主键是否存在
            <#if table?? && table.fields??>
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            if (ObjectUtil.isEmpty(${entity?uncap_first}.get${field.capitalName}())) {
                throw new IllegalArgumentException("${field.comment!''}不能为空");
            }
            </#if>
            </#list>
            
            // 检查记录是否存在
            <#if primaryKeyCount == 1>
            <#-- 单一主键查询 -->
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            ${entity} existEntity = this.getById(${entity?uncap_first}.get${field.capitalName}());
            </#if>
            </#list>
            <#else>
            <#-- 联合主键查询 -->
            final LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            queryWrapper.eq(${entity}::get${field.capitalName}, ${entity?uncap_first}.get${field.capitalName}());
            </#if>
            </#list>
            final ${entity} existEntity = this.getOne(queryWrapper);
            </#if>
            <#else>
            if (ObjectUtil.isEmpty(${entity?uncap_first}.getId())) {
                throw new IllegalArgumentException("ID不能为空");
            }
            
            // 检查记录是否存在
            final ${entity} existEntity = this.getById(${entity?uncap_first}.getId());
            </#if>
            if (ObjectUtil.isEmpty(existEntity)) {
                throw new BusinessException("记录不存在");
            }
            
            // 执行更新
            <#if primaryKeyCount == 1>
            final boolean success = this.updateById(${entity?uncap_first});
            <#else>
            // 联合主键需要使用条件更新
            final LambdaQueryWrapper<${entity}> updateWrapper = new LambdaQueryWrapper<>();
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            updateWrapper.eq(${entity}::get${field.capitalName}, ${entity?uncap_first}.get${field.capitalName}());
            </#if>
            </#list>
            final boolean success = this.update(${entity?uncap_first}, updateWrapper);
            </#if>
            if (!success) {
                throw new BusinessException("更新失败");
            }
        } catch (Exception e) {
            log.error("更新${table.comment!}失败", e);
            throw new BusinessException("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除${table.comment!}
     *
     * @param req 删除条件
     */
    <#if table?? && table.fields??>
    <#-- 检查主键字段数量 -->
    <#assign primaryKeyCount = 0>
    <#list table.fields as field>
        <#if field.keyFlag?? && field.keyFlag>
            <#assign primaryKeyCount = primaryKeyCount + 1>
        </#if>
    </#list>
    <#if primaryKeyCount == 1>
    <#-- 单一主键删除 -->
    <#list table.fields as field>
    <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
    public void del${entity}ById(Del${entity}Req req) {
        try {
            // 检查记录是否存在
            final ${entity} existEntity = this.getById(req.get${field.capitalName}());
            if (ObjectUtil.isEmpty(existEntity)) {
                throw new BusinessException("记录不存在");
            }
            
            // 执行删除
            final boolean success = this.removeById(req.get${field.capitalName}());
            if (!success) {
                throw new BusinessException("删除失败");
            }
        } catch (Exception e) {
            log.error("删除${table.comment!}失败", e);
            throw new BusinessException("删除失败: " + e.getMessage());
        }
    }
    </#if>
    </#list>
    <#else>
    <#-- 联合主键删除 - 必须使用所有主键字段作为一个整体进行删除 -->
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del${entity}ById(Del${entity}Req req) {
        try {
            // 联合主键校验 - 必须同时提供所有主键字段
            StringBuilder missingFields = new StringBuilder();
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            if (ObjectUtil.isEmpty(req.get${field.capitalName}())) {
                missingFields.append(!missingFields.isEmpty() ? ", " : "").append("${field.comment!''}");
            }
            </#if>
            </#list>
            
            if (!missingFields.isEmpty()) {
                throw new IllegalArgumentException("联合主键删除必须同时提供所有主键字段，缺少: " + missingFields);
            }
            
            // 构建联合主键精确匹配条件 - 所有主键字段必须作为一个整体使用
            final LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            queryWrapper.eq(${entity}::get${field.capitalName}, req.get${field.capitalName}());
            </#if>
            </#list>
            
            // 检查记录是否存在
            ${entity} existEntity = this.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(existEntity)) {
                throw new BusinessException("根据完整联合主键条件未找到记录");
            }
            
            // 执行删除 - 必须使用完整的联合主键条件，确保严格匹配一条记录
            final int rowsAffected = this.baseMapper.delete(queryWrapper);
            if (rowsAffected == 0) {
                throw new BusinessException("删除失败: 未找到符合联合主键条件的记录");
            }
            if (rowsAffected > 1) {
                // 这种情况在正确的联合主键约束下不应该发生
                log.error("删除异常: 预期删除1条记录，实际删除{}条记录", rowsAffected);
                throw new BusinessException("删除异常: 联合主键条件匹配到多条记录(" + rowsAffected + ")，已回滚操作");
            }
            
            log.info("成功删除一条记录，联合主键: [" + 
            <#list table.fields as field>
            <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
            <#if field?is_first>"${field.comment!''}: " + req.get${field.capitalName}()<#else> + ", ${field.comment!''}: " + req.get${field.capitalName}()</#if>
            </#if>
            </#list>
            + "]");
        } catch (Exception e) {
            log.error("使用联合主键删除${table.comment!}失败", e);
            throw new BusinessException("删除失败: " + e.getMessage());
        }
    }
    </#if>
    <#else>
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del${entity}ById(Del${entity}Req req) {
        try {
            // 检查记录是否存在
            final ${entity} existEntity = this.getById(req.getId());
            if (ObjectUtil.isEmpty(existEntity)) {
                throw new BusinessException("记录不存在");
            }
            
            // 执行删除
            final boolean success = this.removeById(req.getId());
            if (!success) {
                throw new BusinessException("删除失败");
            }
        } catch (Exception e) {
            log.error("删除${table.comment!}失败", e);
            throw new BusinessException("删除失败: " + e.getMessage());
        }
    }
    </#if>

    /**
     * 按条件删除${table.comment!}
     *
     * @param conditionMap 条件字段和值
     * @return 删除的记录数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int del${entity}ByCondition(Map<String, Object> conditionMap) {
        try {
            if (ObjectUtil.isEmpty(conditionMap)) {
                throw new IllegalArgumentException("删除条件不能为空");
            }
            final QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
            // 设置条件
            conditionMap.forEach((key, value) -> {
                if (value != null) {
                    queryWrapper.eq(key, value);
                }
            });
            return this.baseMapper.delete(queryWrapper);
        } catch (Exception e) {
            log.error("按条件删除${table.comment!}失败", e);
            throw new BusinessException("按条件删除失败: " + e.getMessage());
        }
    }

    /**
    * 批量删除${table.comment!}
    *
    * @param req 删除条件
    */
    <#-- 批量删除处理 -->
    <#if table?? && table.fields??>
    <#-- 检查主键字段数量 -->
    <#assign primaryKeyCount = 0>
    <#list table.fields as field>
        <#if field.keyFlag?? && field.keyFlag>
            <#assign primaryKeyCount = primaryKeyCount + 1>
        </#if>
    </#list>
    <#if primaryKeyCount == 1>
    <#-- 单一主键处理，支持批量删除 -->
    <#list table.fields as field>
    <#if field.propertyName?? && field.keyFlag?? && field.keyFlag>
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete${entity}(BatchDelete${entity}Req req) {
        try {
            if (ObjectUtil.isEmpty(req.get${field.capitalName}s())) {
                throw new IllegalArgumentException("${field.comment!''}列表不能为空");
            }
            
            // 执行批量删除
            final boolean success = this.baseMapper.deleteBatchIds(req.get${field.capitalName}s()) > 0;
            if (!success) {
                throw new BusinessException("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除${table.comment!}失败", e);
            throw new BusinessException("批量删除失败: " + e.getMessage());
        }
    }
    </#if>
    </#list>
    </#if>
    <#else>
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete${entity}(BatchDelete${entity}Req req) {
        try {
            if (ObjectUtil.isEmpty(req.getIds())) {
                throw new IllegalArgumentException("ID列表不能为空");
            }
            
            // 执行批量删除
            final boolean success = this.baseMapper.deleteBatchIds(req.getIds()) > 0;
            if (!success) {
                throw new BusinessException("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除${table.comment!}失败", e);
            throw new BusinessException("批量删除失败: " + e.getMessage());
        }
    }
    </#if>
}
</#if> 